package utils

import (
	"net/url"
)

// URLUtil url转换
type URLUtil struct {
	RawString   string
	QueryObject url.Values
	Fragment    string
	Host        string
	Pathname    string
	Scheme      string
}

// ParseURL 解析url string
func ParseURL(raw string) (*URLUtil, error) {
	var urlObject, err = url.Parse(raw)
	if err != nil {
		return nil, err
	}
	var u = &URLUtil{}
	u.RawString = raw
	u.Scheme = urlObject.Scheme
	u.Host = urlObject.Host
	u.Pathname = urlObject.Path
	u.QueryObject = urlObject.Query()
	u.Fragment = urlObject.Fragment
	return u, nil
}

// SetParam 设置参数
func (u *URLUtil) SetParam(key, value string) {
	u.QueryObject.Set(key, value)
}

// Encode 编码生成url
func (u *URLUtil) Encode() string {
	return u.Scheme + "://" + u.Host + u.Pathname + "?" + u.QueryObject.Encode() + "#" + u.Fragment
}

// Query 获取参数
func (u *URLUtil) Query() url.Values {
	return u.QueryObject
}
